package com.admin.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.common.model.BaseUser;

/**
 * 用于检查进入/admin/目录的用户是否是已登录的管理员
 */
@WebFilter("/admin/*")
public class AdminFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(AdminFilter.class);
    /**
     * Default constructor. 
     */
    public AdminFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// place your code here
		HttpSession session=((HttpServletRequest)request).getSession();
		BaseUser user=(BaseUser)session.getAttribute("user");
		HttpServletRequest httpRequest=(HttpServletRequest)request;
		String accept=httpRequest.getHeader("accept");
		String xhttp=httpRequest.getHeader("X-Requested-With");
		if(accept==null){
			accept="";
		}
		if(xhttp==null){
			xhttp="";
		}
		accept =accept.toLowerCase();
		boolean isJson=false;
		if(accept.indexOf("json")!=-1){
			isJson=true;
		}
		if(user==null){
			logger.info("用户还未登陆,拒绝进入管理员模块");
			if(xhttp.equalsIgnoreCase("XMLHttpRequest")){
				if(isJson){
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("{\"error\":1}");
				}
				else{
					response.getWriter().write("-100");
				}
			}else{
				((HttpServletResponse)response).sendRedirect("/byxt/");
			}
			return;
		}
		else if(!user.getUserType().equals("admin")){
			logger.info("用户身份不正确,拒绝进入管理员模块");
			if(xhttp.equalsIgnoreCase("XMLHttpRequest")){
				if(isJson){
					response.setContentType("application/json");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("{\"error\":2}");
				}
				else{
					response.getWriter().write("-101");
				}
			}else{
				((HttpServletResponse)response).sendRedirect("/byxt/");
			}
			return;
		}

		logger.info("检查通过,进入管理员模块");
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
